"""
UI组件模块：负责创建和管理应用程序的用户界面
包含所有UI相关的类和方法，处理界面布局、主题切换和用户交互
"""

import customtkinter as ctk
from config import COLORS, FONTS, BUTTON_CONFIG, LAYOUT, THEMES

class QuizUI:
    """
    问答系统的UI类，负责创建和管理所有界面元素
    
    属性:
        app: HackerQuizApp实例，用于访问应用程序的核心功能
        root: 主窗口实例
        default_font: 默认字体设置
        button_height: 按钮高度
        visited_questions: 已访问题目的集合
        default_button_color: 默认按钮颜色
    """
    
    def __init__(self, app):
        """
        初始化UI类
        
        参数:
            app: HackerQuizApp实例
        """
        self.app = app
        self.root = app.root
        self.default_font = FONTS["default"]
        self.button_height = BUTTON_CONFIG["height"]
        self.visited_questions = set()
        self.default_button_color = THEMES["黑色主题"]["button_color"]
        self.setup_ui()
    
    def setup_ui(self):
        """设置UI布局，创建主要的框架和组件"""
        self.left_frame = self.create_left_frame()
        self.main_frame = self.create_main_frame()
    
    def create_left_frame(self):
        """
        创建左侧面板，包含主题选择器、上传按钮和题目列表
        
        返回:
            ctk.CTkFrame: 左侧面板实例
        """
        left_frame = ctk.CTkFrame(self.root, width=LAYOUT["left_frame_width"])
        left_frame.pack(side="left", fill="y", padx=LAYOUT["padding"], pady=LAYOUT["padding"])
        
        self.create_theme_selector(left_frame)
        
        # 创建上传按钮
        self.upload_btn = self.create_button(
            left_frame,
            "上传Word文档",
            self.app.upload_file,
            COLORS["success"],
            "black",
            None,
            pack_kwargs={"pady": LAYOUT["padding"]}
        )
        
        # 创建错题本按钮
        self.wrong_btn = self.create_button(
            left_frame,
            "查看错题本",
            self.app.show_wrong_questions,
            COLORS["error"],
            "white",
            None,
            pack_kwargs={"pady": LAYOUT["padding"]}
        )
        
        # 创建题目列表
        self.question_list = ctk.CTkScrollableFrame(
            left_frame,
            width=LAYOUT["left_frame_width"] - 20,
            height=400,
        )
        self.question_list.pack(pady=LAYOUT["padding"], fill="both", expand=True)
        
        return left_frame
    
    def create_theme_selector(self, parent):
        """
        创建主题选择器
        
        参数:
            parent: 父级容器
        """
        theme_frame = ctk.CTkFrame(parent)
        theme_frame.pack(fill="x", padx=LAYOUT["small_padding"], pady=LAYOUT["small_padding"])
        
        theme_label = ctk.CTkLabel(
            theme_frame,
            text="主题风格：",
            font=self.default_font
        )
        theme_label.pack(side="left", padx=LAYOUT["small_padding"])
        
        self.theme_var = ctk.StringVar(value=self.app.current_theme)
        theme_menu = ctk.CTkOptionMenu(
            theme_frame,
            values=list(THEMES.keys()),
            variable=self.theme_var,
            command=self.app.apply_theme,
            font=self.default_font
        )
        theme_menu.pack(side="right", padx=LAYOUT["small_padding"])
    
    def create_main_frame(self):
        """
        创建主要内容区域，包含题目显示、选项和控制按钮
        
        返回:
            ctk.CTkFrame: 主框架实例
        """
        main_frame = ctk.CTkFrame(self.root)
        main_frame.pack(side="right", fill="both", expand=True, padx=LAYOUT["padding"], pady=LAYOUT["padding"])
        
        # 创建题目显示区
        self.question_display = ctk.CTkTextbox(
            main_frame,
            height=LAYOUT["question_height"],
            font=FONTS["title"],
            wrap="word"
        )
        self.question_display.pack(fill="both", expand=True, padx=20, pady=LAYOUT["padding"])
        
        # 创建选项区域
        self.create_options_frame(main_frame)
        
        # 创建答案显示区
        self.answer_display = ctk.CTkTextbox(
            main_frame,
            height=LAYOUT["answer_height"],
            font=FONTS["content"],
            wrap="word"
        )
        self.answer_display.pack(fill="both", expand=True, padx=20, pady=LAYOUT["small_padding"])
        
        # 创建控制按钮
        self.create_control_buttons(main_frame)
        
        return main_frame
    
    def create_options_frame(self, parent):
        """
        创建选项按钮区域
        
        参数:
            parent: 父级容器
        """
        options_frame = ctk.CTkFrame(parent)
        options_frame.pack(fill="x", padx=20, pady=LAYOUT["padding"])
        
        options = ['A', 'B', 'C', 'D']
        for option in options:
            option_btn = ctk.CTkRadioButton(
                options_frame,
                text=option,
                variable=self.app.selected_option,
                value=option,
                font=FONTS["content"],
                command=self.app.check_answer,
                height=BUTTON_CONFIG["small_height"]
            )
            option_btn.pack(side="left", padx=30, pady=LAYOUT["small_padding"])
    
    def create_control_buttons(self, parent):
        """
        创建控制按钮区域，包含导航和功能按钮
        
        参数:
            parent: 父级容器
        """
        button_frame = ctk.CTkFrame(parent)
        button_frame.pack(fill="x", padx=20, pady=LAYOUT["padding"])
        
        # 导航按钮
        self.prev_btn = self.create_button(
            button_frame, "上一题", self.app.prev_question,
            COLORS["success"], "black", "left"
        )
        
        self.next_btn = self.create_button(
            button_frame, "下一题", self.app.next_question,
            COLORS["success"], "black", "left"
        )
        
        # 功能按钮
        self.mark_button = self.create_button(
            button_frame, "标记题目", self.app.toggle_mark_question,
            COLORS["warning"], "black", "right"
        )
        
        self.similar_btn = self.create_button(
            button_frame, "同类型题目", self.app.generate_similar_questions,
            COLORS["purple"], "white", "right"
        )
        
        self.ai_help_btn = self.create_button(
            button_frame, "AI解析", self.app.get_ai_help,
            COLORS["info"], "white", "right"
        )
        
        self.show_answer_btn = self.create_button(
            button_frame, "显示答案", self.app.toggle_answer,
            COLORS["error"], "white", "right"
        )
    
    def create_button(self, parent, text, command, fg_color, text_color, side, pack_kwargs=None):
        """
        通用按钮创建方法
        
        参数:
            parent: 父级容器
            text: 按钮文本
            command: 点击事件处理函数
            fg_color: 按钮颜色
            text_color: 文本颜色
            side: 停靠方向
            pack_kwargs: 额外的pack参数
        
        返回:
            ctk.CTkButton: 按钮实例
        """
        btn = ctk.CTkButton(
            parent,
            text=text,
            command=command,
            fg_color=fg_color,
            text_color=text_color,
            font=self.default_font,
            height=self.button_height,
            width=BUTTON_CONFIG["width"]
        )
        
        pack_args = {"side": side, "padx": LAYOUT["padding"]} if side else {}
        if pack_kwargs:
            pack_args.update(pack_kwargs)
        btn.pack(**pack_args)
        
        return btn
    
    def update_question_buttons(self, questions):
        """
        更新题目列表按钮
        
        参数:
            questions: 题目列表
        """
        for widget in self.question_list.winfo_children():
            widget.destroy()
        
        self.question_buttons = []
        for i, _ in enumerate(questions):
            btn = self.create_button(
                self.question_list,
                f"题目 {i+1}",
                lambda idx=i: self.app.jump_to_question(idx),
                COLORS["visited"] if i in self.visited_questions else None,
                None,
                None,
                pack_kwargs={"pady": 2, "padx": 5, "fill": "x"}
            )
            self.question_buttons.append(btn)
    
    def update_button_states(self, current_index):
        """
        更新按钮状态，包括题目列表和标记按钮
        
        参数:
            current_index: 当前题目索引
        """
        if not hasattr(self.app, 'questions') or not self.app.questions:
            return
        
        for i, btn in enumerate(self.question_buttons):
            if i == current_index:
                btn.configure(fg_color=COLORS["success"])
            elif i in self.visited_questions:
                btn.configure(fg_color=COLORS["visited"])
            elif self.app.questions[i] in self.app.marked_questions:
                btn.configure(fg_color=COLORS["warning"])
            else:
                btn.configure(fg_color=self.default_button_color)
        
        current_question = self.app.questions[current_index]
        if current_question in self.app.marked_questions:
            self.mark_button.configure(text="取消标记", fg_color=COLORS["marked"])
        else:
            self.mark_button.configure(text="标记题目", fg_color=COLORS["warning"])
        
        self.visited_questions.add(current_index)
    
    def create_ai_help_window(self):
        """
        创建AI帮助窗口
        
        返回:
            tuple: (窗口实例, 加载框架, 加载标签)
        """
        ai_window = ctk.CTkToplevel(self.root)
        ai_window.title("AI题目解析")
        ai_window.geometry(LAYOUT["ai_window_size"])
        
        loading_frame = ctk.CTkFrame(ai_window)
        loading_frame.pack(pady=20)
        
        loading_label = ctk.CTkLabel(
            loading_frame,
            text="正在分析题目...",
            font=self.default_font
        )
        loading_label.pack(pady=LAYOUT["small_padding"])
        
        progress = ctk.CTkProgressBar(loading_frame)
        progress.pack(pady=LAYOUT["small_padding"])
        progress.configure(mode="indeterminate")
        progress.start()
        
        return ai_window, loading_frame, loading_label 